package com.beans;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.SelectEvent;
import org.springframework.context.annotation.Scope;

import com.controllers.CommentController;
import com.controllers.EmailController;
import com.controllers.EmployeeController;
import com.controllers.TaskController;
import com.model.Activity;
import com.model.Comment;
import com.model.Employee;
import com.model.Task;
import com.utils.DateUtils;

@Named
@Scope(value = "session")
public class EmployeeTasksBean {

	private TaskController taskController;

	private Task selectedTask;

	private Comment newComment;

	private int selectedProgress;

	private DataTable tasksTable;

	private CommentController commentController;

	private List<Comment> comments;

	private List<Task> tasks;

	private EmployeeController employeeController;

	private Employee loggedInEmployee;

	@Inject
	public EmployeeTasksBean(TaskController taskController,
			EmployeeController employeeController,
			CommentController commentController) {
		this.taskController = taskController;
		this.commentController = commentController;
		this.employeeController = employeeController;
		newComment = new Comment();
	}

	public void init(ComponentSystemEvent event) {
		if (!FacesContext.getCurrentInstance().isPostback()) {
			tasks = taskController.getTasksToBeApprovedOrderByDeadLine();
			comments = new ArrayList<Comment>();
			
			loggedInEmployee = employeeController
					.getLoggedInUser(employeeController.getCurrentUsername());
		}
	}

//	public List<Task> getTasksForEmployee() {
//		String username = FacesContext.getCurrentInstance()
//				.getExternalContext().getRemoteUser();
//		return new ArrayList<Task>(
//				taskController.getTasksForEmployeeByUsername(username));
//	}

	public void showCommentsForTask(SelectEvent event) {
		Task task = (Task) event.getObject();
		comments = commentController.getCommentsForTask(task.getId());
	}

	public void updateProgress(ActionEvent event) {
		selectedTask = (Task) tasksTable.getRowData();
		selectedProgress = selectedTask.getProgress();
		showRightEmployeeInSelectMenu();
	}

	private void showRightEmployeeInSelectMenu() {
		for (Employee employee : TasksTableBean.employees) {
			if (employee.getId() == selectedTask.getEmployee().getId()) {
				selectedTask.setEmployee(employee);
			}
		}
	}

	public void saveComment(ActionEvent actionEvent) {

		if (selectedTask == null) {
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(
									FacesMessage.SEVERITY_ERROR,
									"El comentario no ha sido agregado, seleccione una tarea antes de agregar un comentario",
									""));
			return;
		}
		String username = employeeController.getCurrentUsername();

		Employee employee = employeeController.getEmployeeByUsername(username);
		commentController.save(newComment, selectedTask, employee,
				selectedProgress);
		// Si aprete el boton sin seleccionar un task comments es null
		if (comments == null)
			comments = commentController.getCommentsForTask(selectedTask
					.getId());
		// si no lo fui a buscar a la base, necesito agregarlo al comments
		// actual
		else
			comments = commentController.getCommentsForTask(selectedTask.getId());
		Collections.sort(comments, new Comparator<Comment>() {
			@Override
			public int compare(Comment o1, Comment o2) {
				return -o1.getDate().compareTo(o2.getDate());
			}

		});
		// Thread emailController = new Thread( new
		// EmailController(selectedTask.getActivity().getEmployeeCreator().getEmail(),
		// newComment, username, 0));
		// emailController.start();
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage("El comentario ha sido agregado"));
		newComment = new Comment();
	}

	public void showMyTasks(ActionEvent event) {
		Employee loggedInUser = employeeController
				.getLoggedInUser(employeeController.getCurrentUsername());
		tasks = taskController.getTasksForEmployee(loggedInEmployee.getId());
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage("Mostrando tareas del usuario "
						+ loggedInUser.getFirstname() + " "
						+ loggedInUser.getLastname()));
	}

	public void showAllTasksToBeApproved(ActionEvent event) {
		tasks = taskController.getTasksToBeApprovedOrderByDeadLine();
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage("Mostrando todas las tareas a aprobar "));

	}
	
	public void showAllDueTasks(ActionEvent event) {
		tasks = taskController.getAllDueTasks();
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage("Mostrando todas las tareas vencidas al:  "+ DateUtils.getCurrentDateWithoutTime())); 

	}
	

	public Task getSelectedTask() {
		return selectedTask;
	}

	public void setSelectedTask(Task selectedTask) {
		this.selectedTask = selectedTask;
	}

	public Comment getNewComment() {
		return newComment;
	}

	public void setNewComment(Comment newComment) {
		this.newComment = newComment;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void setTasks(List<Task> tasks) {
	}

	public List<Comment> getComments() {
		return comments;
	}

	public void setComments(List<Comment> comments) {
		this.comments = comments;
	}

	public int getSelectedProgress() {
		return selectedProgress;
	}

	public void setSelectedProgress(int selectedProgress) {
		this.selectedProgress = selectedProgress;
	}

	public DataTable getTasksTable() {
		return tasksTable;
	}

	public void setTasksTable(DataTable tasksTable) {
		this.tasksTable = tasksTable;
	}

}
